#!/bin/bash
#########################################################################
# Author: qianqiang@jd.com
PLATFORM=$1
JDREACT_MODULE=$2
ACCESSKEY=$3
SECRETKEY=$4
ROOT_DIR=$(cd ..;pwd)
bundle_githash=`git log -1 --oneline | cut -d ' ' -f1`
bundle_version=$(cat 'sdk.version')
doErrorExit () {
  cd $ROOT_DIR
  echo "build error!!"
  exit 1
}
doExit ( ) {
  echo "build suceess!!"
}
cd $ROOT_DIR
upgrade_version=$(echo "version=`cat ./jsbundles/$JDREACT_MODULE.version`" | grep "moduleCode" | grep -o "[0-9]\+.[0-9]\+")
# build jdreact jsbundle
if [ $PLATFORM == 'android' ]; then
  echo ">>>>>> Starting to build Android jsbundles ...."
  build_result=`./scripts/make-fullpack-jsbundles.sh -p android -m $JDREACT_MODULE`
  echo "$build_result"
  if [[ $build_result =~ "failed" ]]; then
    echo ">>>>>> jsbundle build failed!!! ...."
    doErrorExit
  fi
elif [ $PLATFORM == 'ios' ]; then
  echo ">>>>>> Starting to build iOS jsbundles ...."
  build_result=`./scripts/make-fullpack-jsbundles.sh -p ios -m $JDREACT_MODULE`
  echo "$build_result"
  if [[ $build_result =~ "failed" ]]; then
    echo ">>>>>> jsbundle build failed!!! ...."
    doErrorExit
  fi
else
  echo "platform is wrong! just exit!"
  doErrorExit
fi
if [ -f outputBundle/$JDREACT_MODULE.so ]; then
  echo ">>>>>> build successfully!"
  filesize=`ls -l outputBundle/$JDREACT_MODULE.so | awk '{ print $5 }'`
  echo "so file size is $filesize"
else
  echo ">>>>>> cannot find $JDREACT_MODULE.so file, so exit!"
  doErrorExit
fi
echo ">>>>>> start to upload..."
cd node_modules/@areslabs/jdreact-core-scripts/bin/
source ./cloudUploader-new-console.sh "$JDREACT_MODULE" "$ROOT_DIR/outputBundle/$JDREACT_MODULE.so" "$ROOT_DIR/SCANME.png" "$PLATFORM" "$ACCESSKEY" "$SECRETKEY"
upgrade_url=$UPLOAD_URL
if [ "$upgrade_url" == "" ]; then
	doErrorExit
fi
echo ">>>>>> start to upload map file! to cloud!!"
source ./cloudUploader-source-map.sh "$JDREACT_MODULE" "$ROOT_DIR/outputBundle/$JDREACT_MODULE.map" "${MODULE_CODE}" "${PLATFORM}" "${COMMIT_ID}" "$ACCESSKEY" "$SECRETKEY"
upgrade_map_url=$UPLOAD_URL
if [ "$upgrade_map_url" == "" ]; then
  doErrorExit
fi
echo "upgrade_url:$upgrade_url"
echo "upgrade_map_url:$upgrade_map_url"
echo "bundle_githash:$bundle_githash"
echo "bundle_version:$bundle_version"
echo "upgrade_version:$upgrade_version"
doExit
